package cn.monkey.io.transport.netty;

import cn.monkey.io.transport.core.AbstractExchangeManager;
import cn.monkey.io.transport.core.Exchange;
import cn.monkey.io.transport.core.ExchangeFactory;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;

import java.util.Map;
import java.util.function.Consumer;

public abstract class AbstractNettyExchangeManager<EXCHANGE extends NettyExchange>
        extends AbstractExchangeManager<Channel, EXCHANGE>
        implements NettyExchangeManager<EXCHANGE> {

    public AbstractNettyExchangeManager(ExchangeFactory<Channel, EXCHANGE> factory) {
        super(factory);
    }

    @Override
    public EXCHANGE findOrCreate(String key, Channel channel) {
        AttributeKey<EXCHANGE> attributeKey = AttributeKey.valueOf(Exchange.KEY);
        EXCHANGE exchange = channel.attr(attributeKey).get();
        if (exchange != null) {
            return exchange;
        }
        return super.exchangeMap.compute(key, (k, v) -> {
            if (v == null || !v.isActive()) {
                return this.factory.apply(k, null, channel);
            }
            return this.factory.apply(k, v, channel);
        });
    }
}
